//////////////////////////////
// serial buffer loading
const int _iMaxSerialBuffer = 512;
int _iSerialBufferStart=0, _iSerialBufferLen=0, _iSerialBufferIndex=0;
char _SerialBuffer[_iMaxSerialBuffer];
boolean readSerialString (String &cmd) {
  int sb;
  while (Serial1.available())
  {
    sb = Serial1.read();
    Serial.print("btr='");
    Serial.print(sb);
    Serial.println("'");
    if(sb=='#') // start cmd ?
    {
      _iSerialBufferStart = _iSerialBufferIndex+1;
    }
    else if(sb=='$' && _iSerialBufferStart>=0) // end cmd ?
    {
      _iSerialBufferLen = _iSerialBufferIndex;
      _SerialBuffer[_iSerialBufferLen] = '\0';
      cmd = &_SerialBuffer[_iSerialBufferStart];
      _iSerialBufferIndex = 0;
      _iSerialBufferStart = -1;
      return true;
    }
    if(_iSerialBufferIndex>=_iMaxSerialBuffer)
    {
      _iSerialBufferIndex = 0;
      _iSerialBufferStart = -1;
      return false;
    }
    _SerialBuffer[_iSerialBufferIndex] = sb;
    _iSerialBufferIndex++;
  }

  return false;
}

///////////////////////////////
// check commands sended
int load_int(String &s, const int start, int &iRet)
{
  int iLen = start+1;
  String num="";

  if (s[start] == '-') num += "-";
  else if(s[start] == '+') num += "";
  else return start;

  for(int i=1; i<6 && s.length()>(start+i); i++)
  {
    char c = s[start+i];
    if(!isDigit(c))
      break;
    num += c;
    iLen ++;
  }

  iRet = num.toInt();
  return iLen;
}
int load_int_nosigne(String &s, const int start, int &iRet)
{
  int iLen = start;
  String num="";

  if (s[start] == '-') num += "-";
  else if(s[start] == '+') num += "";

  for(int i=0; i<6 && s.length()>(start+i); i++)
  {
    char c = s[start+i];
    if(!isDigit(c))
      break;
    num += c;
    iLen ++;
  }

  iRet = num.toInt();
  return iLen;
}

boolean check_commands(void)
{
  String line="";
  if(!readSerialString(line))
    return false;
  if(line.length()>0)
  {
    // debug only : send_message(line);

    switch(line[0])
    {
    case 'v': // (V)ersion
      {
        // #v$
        send_version();
      }
      break;
    case 'a': // (A)nimation
      {
        // #as0$
        switch(line[1])
        {
        case 's': // (S)tart
          {
            int aloop=0;
            int next = load_int_nosigne(line, 3, aloop);
            if(aloop<N_ANIM_LOOPS) start_animation(loops[aloop]);
            else send_error("animation unknown");
          }
          break;
        }
      }
      break;
    default:
      {
        String sError = "invalid cmd '" + line + "'";
        send_error(sError);
      }
      break;
    }
    return true;
  }
  return false;
}



